package cn.yunhe.service;

import cn.yunhe.dao.ICarDao;
import cn.yunhe.entity.Car;
import cn.yunhe.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class ICarService {
    SqlSession sqlSession = SqlSessionFactoryUtil.getSqlSession();
    ICarDao carDao = sqlSession.getMapper(ICarDao.class);

    public List<Car> getAllCar() {

        try {
            List<Car> carList = carDao.getAllCar();
            return carList;
        } finally {
            sqlSession.close();
        }
    }


    /**
     * 添加车辆
     *
     * @param car
     * @return
     */
    public boolean addCar(Car car) {

        try {
            boolean flag = carDao.addCar(car);
            if (flag) {
                sqlSession.commit();
                return true;
            } else {
                return false;
            }
        } finally {

        }
    }

    /**
     * 根据Id 查询指定车辆
     *
     * @param indexId
     * @return
     */
    public Car getCarById(int indexId) {
        try {
            return carDao.getCarById(indexId);
        } finally {
            sqlSession.close();
        }

    }

    /**
     * 编辑车辆信息
     *
     * @param car
     * @return
     */
    public boolean updateCar(Car car) {
        try {
            boolean flag = carDao.updateCar(car);
            if (flag) {
                sqlSession.commit();
                return true;
            } else {
                return false;
            }
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 获得车辆总条数
     *
     * @return
     */
    public int countCar() {
        try {
            return carDao.countCar();
        } finally {

        }
    }


    /**
     * 删除车辆信息
     *
     * @param indexId
     * @return
     */
    public boolean delCar(int indexId) {
        try {
            if (carDao.delCar(indexId)) {
                sqlSession.commit();
                return true;
            } else {
                return false;
            }

        } finally {
            sqlSession.close();
        }
    }

    /**
     * 模糊查询
     *
     * @param keyword
     * @return
     */
    public List<Car> searchCar(String keyword){
        try {
            return carDao.searchCar(keyword);
        }finally {
            sqlSession.close();
        }
    }

    /**
     * 批量删除
     *
     * @param checkedId
     * @return
     */
    public boolean falseDelete(String checkedId){
        try {
            if (carDao.falseDelete(checkedId.split(","))){
                sqlSession.commit();
               return true;
            }else {
                return false;
            }
        }finally {
            sqlSession.close();
        }
    }
}